package com.yunshu.yunshuapp.xianhuo;

import android.content.Intent;
import android.os.Bundle;

import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.kuaixun.KuaixunSubscribeActivity;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.tongxunlu.ButtonsListActivity;
import com.yunshu.yunshuapp.user.LoginActivity;
import com.yunshu.yunshuapp.user.YSUser;
import com.yunshu.yunshuapp.utils.YSUtils;
import com.yunshu.yunshuapp.views.SegmentControlView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

public class XianhuoActivity extends ButtonsListActivity implements Toolbar.OnMenuItemClickListener {

    private int pageIndex = 1;
    private String channelName= "";
    private String cities = "";
    private YSRequest request1 = new YSRequest(this);
    protected XianhuoListAdapter adapter;
    private int listType = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        navigationBar.setOnMenuItemClickListener(this);

        SegmentControlView segment = new SegmentControlView(this);
        segment.setTexts(new String[]{"现货","采购"});
        segment.setFrameCornerRadius(20);
        //该布局在LinearLayout下
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);//addRule参数对应RelativeLayout XML布局的属性
        lp.setMargins(YSUtils.screenWidth(this)/4,0,YSUtils.screenWidth(this)/4,0);
        lp.height = navigationBar.getLayoutParams().height /2;
        segment.setLayoutParams(lp);
        navigationBar.addView(segment);
        segment.setOnSegmentChangedListener(new SegmentControlView.OnSegmentChangedListener() {
            @Override
            public void onSegmentChanged(int newSelectedIndex) {
                changeListType(newSelectedIndex);
            }
        });
        //set viewpager to change segment according to the state of viewpager
        //set the selected index of segments initiatively
        segment.setSelectedIndex(0);
        navigationBar.setTitle(null);

        this.mTypeAdapter.allowMultiSelect = true;
    }

    private void changeListType(int newSelectedIndex) {
        if (listType == newSelectedIndex) return;
        listType = newSelectedIndex;
        this.refresh();
    }

    protected void initRecyleView() {
        super.initRecyleView();

        adapter = new XianhuoListAdapter(getBaseContext());
        adapter.activity = this;
        mRecyclerView.setAdapter(adapter);

    }

    protected void refresh() {
        if (!request1.getIsCompleted()) return;
        pageIndex = 1;
        String params = "audit=1&page=1" + "&place="+cities+"&type="+listType;
        if (channelName != null && channelName.length() > 0){
            params = "audit=1&page=1&channelname="+channelName + "&place="+cities+"&type="+listType;
        }
        request1.GET(YSRequest.XIANHUO_LIST, params, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (result == null || !result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<Xianhuo> temp = new ArrayList<Xianhuo>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        Xianhuo model = mapper.readValue(jsonstr, Xianhuo.class);
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                adapter.setModels(temp);
                pageIndex +=1;
                reloadData();
            }
        });
    }

    private void reloadData() {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }
    private void endRefreshing() {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(false);
            }
        });

    }

    protected void loadmore() {
        if (!request1.getIsCompleted()) return;

        String params = "audit=1&page="+ pageIndex + "&place="+cities+"&type="+listType;
        if (channelName != null && channelName.length() > 0){
            params = "audit=1&page="+ pageIndex+"&channelname="+channelName + "&place="+cities+"&type="+listType;
        }
        request1.GET(YSRequest.XIANHUO_LIST, params, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (!result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<Xianhuo> temp = new ArrayList<Xianhuo>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        Xianhuo model = mapper.readValue(jsonstr, Xianhuo.class);
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                pageIndex +=1;
                adapter.addFooterItem(temp);
                reloadData();
            }
        });
    }


    @Override
    protected void onFilterChange(String types, String cities) {
        this.channelName = types;
        this.cities = cities;
        this.refresh();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_xianhuo , menu);
        return true;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_subscribeKuaixun:

                Intent intent = new Intent();
                if (YSUser.isLogin()) {
                    intent.setClass(this, PostCenterActivity.class);
                }else{
                    intent.setClass(this, LoginActivity.class);
                }
                startActivityForResult(intent, 0);
                break;
            default:break;
        }
        return true;
    }
}
